package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.ScenicComment;
import cn.wolfcode.luowowo.comment.query.ScenicCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ScenicCommentRepository;
import cn.wolfcode.luowowo.comment.service.IScenicCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Optional;


@Service
public class ScenicCommentServiceImpl implements IScenicCommentService {

    @Autowired
    private ScenicCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    //景点评论保存
    @Override
    public void save(ScenicComment record) {

        repository.save(record);
    }

    //分页
    @Override
    public Page query(ScenicCommentQuery qo) {
        Query query = new Query();

        //条件查询
        if (qo.getScenicId() != -1) {
            query.addCriteria(Criteria.where("scenicId").is(qo.getScenicId()));
        }

        //分页条件,不要忘记减一
        PageRequest pageRequest = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "creatTime");

        long count = template.count(query, ScenicComment.class);

        query.with(pageRequest);

        List<ScenicComment> list = template.find(query, ScenicComment.class);

        return new PageImpl(list,pageRequest, count);
    }

    //点赞
    @Override
    public void findById(String scenicCommentId,Long userId) {

        Optional<ScenicComment> comment = repository.findById(scenicCommentId);
        ScenicComment scenicComment = comment.get();

        //判断集合中是否存在userId
        List<Long> list = scenicComment.getThumbuplist();
        if(list.contains(userId)){
            throw new RuntimeException("您已经点过赞了");
        }

        scenicComment.setThumbupnum(scenicComment.getThumbupnum() +1 ); //点赞数+1
        scenicComment.getThumbuplist().add(userId); //把当前用户id设置到集合中

        repository.save(scenicComment);
    }

    @Override
    public List<ScenicComment> getFavoriteScenicByUserId(Long userId) {

        List<ScenicComment> comments = repository.findByUserId(userId);

        return comments;
    }
}
